<?php


namespace App\Model\Logic;

use App\Exception\HttpException;
use Swoft\Bean\Annotation\Mapping\Bean;
use App\Model\Dao\CourseDao;
use Swoft\Bean\Annotation\Mapping\Inject;

/**
 * Class CourseLogic
 * @Bean(name="CourseLogic")
 * @package App\Model\Logic
 */
class CourseLogic
{
    /**
     * @Inject()
     * @var CourseDao
     */
    private $courseDao;

    public function addData($data){
        //数据验证
        validate($data, 'CourseValidator');
        //更新到数据表
        if($this->courseDao->add($data)){
            throw new HttpException("添加成功",0);
        }
        throw new HttpException("添加失败");
    }

    /**
     * 数据的查询与分页
     * @param $params
     * @return array
     */
    public function getDatas($params)
    {
        $where= [];
        if(isset($params['title'])){
            $where= [
                ["title",'like',"%".$params['title']."%"]
            ];
        }
        $datas = [
            'page'=>$params["page"]??1,
            'limit'=>$params["limit"]??15,
            'where'=>$where
        ];
        $data =  $this->courseDao->getDatas($datas);
        $datas = [
            "code"=>0,
            "msg"=>"ok",
            "count"=>$data['count'],
            "data"=>$data['data']
        ];
        return $datas;
    }

    /**
     * 设置状态
     * @param $data
     * @throws HttpException
     */
    public function setIsShow($data)
    {
        if($this->courseDao->setIsShow($data)){
            throw new HttpException("操作成功",0);
        }
        throw new HttpException("操作失败");
    }

    /**
     * 通过ID获取课程信息
     * @param $id
     * @return mixed
     * @throws HttpExecption
     */
    public function getCourseFromId(int $id)
    {
        $result = $this->courseDao->getCourseFromId($id);
        if($result!==false){
            return $result;
        }
        throw new HttpException("课程不存在");
    }

    /**
     * 更新入库
     * @param $data
     * @throws HttpExecption
     * @throws \ReflectionException
     * @throws \Swoft\Bean\Exception\ContainerException
     * @throws \Swoft\Db\Exception\DbException
     * @throws \Swoft\Validator\Exception\ValidatorException|HttpException
     */
    public function updateData($data)
    {
        //数据验证
        validate($data,"CourseValidator");
        //更新到数据表
        if($this->courseDao->updateData($data)){
            throw new HttpException("更新成功",0);
        }
        throw new HttpException("更新失败");
    }

    /**
     * 删除
     * @param $ids
     * @throws HttpExecption
     * @throws \ReflectionException
     * @throws \Swoft\Bean\Exception\ContainerException
     * @throws \Swoft\Db\Exception\DbException
     */
    public function del($ids){
        $ids = explode(",",$ids);
        if($this->courseDao->del($ids)){
            throw new HttpException("删除成功",0);
        }else{
            throw new HttpException("添加失败");
        }
    }
}
